package com.ruoyi.htgl.htbz.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WordUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.word.WordOperation;
import com.ruoyi.htgl.htbz.domain.*;
import com.ruoyi.htgl.htbz.service.IHtglHtbzService;
import com.ruoyi.infoRunTaskData.domain.InfoRunTaskData;
import com.ruoyi.infoRunTaskData.service.IInfoRunTaskDataService;
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.formatting.ParagraphFormat;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

/**
 * 合同编制Controller
 *
 * @author huacai
 * @date 2024-07-03
 */
@RestController
@RequestMapping("/htbz/htbz")
public class HtglHtbzController extends BaseController {
    @Value(value = "${ruoyi.profile}")
    private String profile;

    private final String temporaryFilePath = "/temporary/";

    @Resource
    private IHtglHtbzService htglHtbzService;

    @Resource
    private IInfoRunTaskDataService iInfoRunTaskDataService;

    /**
     * 查询合同编制列表
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:list')")
    @GetMapping("/list")
    public TableDataInfo list(HtglHtbz htglHtbz) {
        startPage();
        List<HtglHtbz> list = htglHtbzService.selectHtglHtbzList(htglHtbz);
        return getDataTable(list);
    }

    /**
     * 导出合同编制列表
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:export')")
    @Log(title = "合同编制", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HtglHtbz htglHtbz) {
        List<HtglHtbz> list = htglHtbzService.selectHtglHtbzList(htglHtbz);
        ExcelUtil<HtglHtbz> util = new ExcelUtil<HtglHtbz>(HtglHtbz.class);
        util.exportExcel(response, list, "合同编制数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<HtglHtbz> util = new ExcelUtil<HtglHtbz>(HtglHtbz.class);
        util.importTemplateExcel(response, "合同编制数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "合同编制", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('htbz:htbz:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<HtglHtbz> util = new ExcelUtil<HtglHtbz>(HtglHtbz.class);
        InputStream inputStream = file.getInputStream();
        List<HtglHtbz> list = util.importExcel(inputStream);
        inputStream.close();
        int count = htglHtbzService.batchInsertHtglHtbz(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取合同编制详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:query')")
    @GetMapping(value = "/{htbzId}")
    public AjaxResult getInfo(@PathVariable("htbzId") String htbzId) {
        return success(htglHtbzService.selectHtglHtbzByHtbzId(htbzId));
    }

    /**
     * 新增合同编制
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:add')")
    @Log(title = "合同编制", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HtglHtbz htglHtbz) {
        htglHtbz.setUserId(Math.toIntExact(getUserId()));
        int i = htglHtbzService.insertHtglHtbz(htglHtbz);
        //向流程业务表中加入数据
        InfoRunTaskData infoRunTaskData = new InfoRunTaskData();
        infoRunTaskData.setBusinessKey(htglHtbz.getHtbzId());
        infoRunTaskData.setBusinessType(4); //业务模块: 合同管理-合同编制
        infoRunTaskData.setBusinessTitle(htglHtbz.getHtName()); //任务名称: 合同名称
        infoRunTaskData.setApplyUser(SecurityUtils.getLoginUser().getUser().getNickName());//申请人

        iInfoRunTaskDataService.insertInfoRunTaskData(infoRunTaskData);

        return toAjax(i);
    }

    /**
     * 修改合同编制
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:edit')")
    @Log(title = "合同编制", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HtglHtbz htglHtbz) {
        //修改业务中间表关系数据
        InfoRunTaskData infoRunTaskData = new InfoRunTaskData();
        infoRunTaskData.setBusinessTitle(htglHtbz.getHtName()); //任务名称: 合同名称
        infoRunTaskData.setBusinessKey(htglHtbz.getHtbzId());
        infoRunTaskData.setBusinessType(4); //业务模块: 合同管理-合同编制
        iInfoRunTaskDataService.updateInfoRunTaskDatas(infoRunTaskData); //注意updateInfoRunTaskDatas

        return toAjax(htglHtbzService.updateHtglHtbz(htglHtbz));
    }

    /**
     * 删除合同编制
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:remove')")
    @Log(title = "合同编制", businessType = BusinessType.DELETE)
    @DeleteMapping("/{htbzIds}")
    public AjaxResult remove(@PathVariable String[] htbzIds) {
        //同时删除业务关系数据
        for (String htbzId : htbzIds) {
            HtglHtbz htglHtbz = htglHtbzService.selectHtglHtbzByHtbzId(htbzId);
            iInfoRunTaskDataService.deleteData(htglHtbz.getHtbzId(), 4);//业务模块: 人才平台-人员申请
        }
        return toAjax(htglHtbzService.deleteHtglHtbzByHtbzIds(htbzIds));
    }

    /**
     * 获得合同编制ID
     */
    @GetMapping("/getHtBzId")
    public AjaxResult getHtBzId() {
        String htBzId = IdUtils.fastSimpleUUID();
        return success(htBzId);
    }

    /**
     * 新增附件
     */
    @PostMapping("/add/File/By/subId")
    public AjaxResult insertHtFjByHtBzId(@RequestBody HtglHtbzFj htglHtbzFj) {
        return toAjax(htglHtbzService.insertHtFjByHtBzId(htglHtbzFj));
    }

    /**
     * 根据主表ID查询附件列表
     */
    @GetMapping("/get/FileList/By/subId")
    public AjaxResult selectHtBzFjList(String sId) {
        HtglHtbzFj htglHtbzFj = new HtglHtbzFj();
        htglHtbzFj.setHtbzId(sId);
        return AjaxResult.success(htglHtbzService.selectHtBzFjList(htglHtbzFj));
    }

    /**
     * 获取合同编制与年度计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:query')")
    @GetMapping(value = "/ndjh/{htbzId}")
    public AjaxResult selectHtglHtbzNdjhByHtbzId(@PathVariable("htbzId") String htbzId) {
        return success(htglHtbzService.selectHtglHtbzNdjhByHtbzId(htbzId));
    }

    /**
     * 获取合同编制与项目预算经费详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:query')")
    @GetMapping(value = "/ysjf/{htbzId}")
    public AjaxResult selectHtglHtbzYsJfByHtbzId(@PathVariable("htbzId") String htbzId) {
        return success(htglHtbzService.selectHtglHtbzYsJfByHtbzId(htbzId));
    }

    /**
     * 获取合同编制与项目经费支付计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:query')")
    @GetMapping(value = "/zfjh/{htbzId}")
    public AjaxResult selectHtglHtbzZfJhByHtbzId(@PathVariable("htbzId") String htbzId) {
        return success(htglHtbzService.selectHtglHtbzZfJhByHtbzId(htbzId));
    }

    /**
     * 获取合同编制与课题承担人员详细信息
     */
    @PreAuthorize("@ss.hasPermi('htbz:htbz:query')")
    @GetMapping(value = "/cdry/{htbzId}")
    public AjaxResult selectHtglHtbzCdRyByHtbzId(@PathVariable("htbzId") String htbzId) {
        return success(htglHtbzService.selectHtglHtbzCdRyByHtbzId(htbzId));
    }

    /**
     * 删除合同附件
     */
    @Log(title = "合同附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/fj/{fjIds}")
    public AjaxResult remove(@PathVariable Integer[] fjIds)
    {
        return toAjax(htglHtbzService.deleteHtglHtbzFjByFjIds(fjIds));
    }

    /**
     * 根据模板导出word
     *
     * @param htbzId   合同编制ID
     * @param request  HttpServlet请求对象
     * @param response 扩展Servlet响应接口，以便在发送响应时提供特定于HTTP的功能。
     * @return docx
     */
    @Log(title = "根据模板导出word", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('occupation:basics:exportWord')")
    @GetMapping("/exportWord/{htbzId}")
    public AjaxResult exportHtbzWord(@PathVariable("htbzId") String htbzId, HttpServletRequest request, HttpServletResponse response) {
        HtglHtbz htbz = htglHtbzService.selectHtglHtbzNdjhByHtbzId(htbzId);

        // 创建一个 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat sdfYM = new SimpleDateFormat("yyyy-MM");
        Date getqTime = htbz.getqTime();//获取起时间
        String qTime = sdfYM.format(getqTime); // 使用 SimpleDateFormat 对象将 Date 对象格式化为 String 对象
        Date getzTime = htbz.getzTime(); //获取止时间
        String zTime = sdfYM.format(getzTime); // 使用 SimpleDateFormat 对象将 Date 对象格式化为 String 对象

        //获取签订日期
        Date qdTime = htbz.getQdTime();
        // 使用 Calendar 提取年、月、日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(qdTime);
        int year = calendar.get(Calendar.YEAR); //年
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH); //日


        Map<String, Object> map = new HashMap<>();

        map.put("htBh", htbz.getHtBh()); //合同编号
        map.put("mj", htbz.getMj()); //密级
        map.put("glXm", htbz.getGlXm()); //项目名称
        map.put("htName", htbz.getHtName()); //课题名称
        map.put("qTime", qTime); //起时间
        map.put("zTime", zTime); //止时间
        map.put("cdDw", htbz.getCdDw()); //承担单位
        map.put("fzName", htbz.getFzName()); //负责人
        map.put("fzDz", htbz.getFzDz()); //通信地址
        map.put("fzYb", htbz.getFzYb()); //邮编
        map.put("fzYx", htbz.getFzYx()); //邮箱
        map.put("fzPhone", htbz.getFzPhone()); //电话
        map.put("fzCz", htbz.getFzCz()); //传真
        map.put("yfFr", htbz.getYfFr()); //法人/授权代表
        map.put("khYh", htbz.getKhYh()); //开户银行
        map.put("yhZh", htbz.getYhZh()); //银行账号
        map.put("khName", htbz.getKhName()); //开户名称
        map.put("year", year); //签订日期中的年
        map.put("month", month); //签订日期中的月
        map.put("day", day); //签订日期中的日

        String str = htbz.getHtName() + ".docx";
        //获取yml配置地址
        String tempDir = "D:/ruoyi/uploadPath" + "/upload/";
        String name = WordUtil.easyPoiExport("static/word/htbz/htbz1.docx", tempDir, str, map, request, response);

        String finalMergeFilePath = "";

        try {
            //临时文件名称
            String zyYjNrFileName = "主要研究内容";
            //富文本内容
            String yYjNr = htbz.getZyYjNr(); //课题主要技术内容 富文本格式
            String zyJsNd = htbz.getZyJsNd(); //主要技术难点
            String yjlxYjff = htbz.getYjlxYjff(); //研究路线及研究方法

            //内容补充
            String firstHtmlContext = "<p><b>1、课题主要技术内容</b></p>"
                    + yYjNr
                    + "<p></p><p></p><p><b>2、主要技术难点</b></p>"
                    + zyJsNd
                    + "<p></p><p></p><p><b>3、研究路线及研究方法</b></p>"
                    + yjlxYjff;
            //一、主要研究内容
            String s = WordOperation.htmlStringToWord(firstHtmlContext, zyYjNrFileName, "二、主要研究内容");
            //去水印
            WordOperation.removeWaterMark(s, 69);

            //第一次合并
            String finalFilePath = WordOperation.mergeDocx(tempDir + str, s, profile + temporaryFilePath + "firstMergeDoc.docx");

            //去水印
            WordOperation.removeWaterMark(finalFilePath, 69);
            //删除临时文件
            WordOperation.deleteTempFile(tempDir + str);
            WordOperation.deleteTempFile(s);

            //三、主要技术经济指标
            //临时文件名称
            String xmYjNrFileName = "主要技术经济指标";
            //富文本内容
            String zyJsJjZb = htbz.getJsJjZb(); //主要技术经济指标 富文本格式

            //内容补充
            String secondHtmlContext = "<p><b> </b></p>"
                    + zyJsJjZb;

            //三、主要技术经济指标
            String s2 = WordOperation.htmlStringToWord(secondHtmlContext, xmYjNrFileName, "三、主要技术经济指标");
            //去水印
            WordOperation.removeWaterMark(s2, 69);
            //第二次合并
            String finalFilePath2 = WordOperation.mergeDocxFile(finalFilePath, s2, profile + temporaryFilePath + "secondMergeDoc.docx");

            WordOperation.removeWaterMark(finalFilePath2, 69);
            //删除临时文件
            WordOperation.deleteTempFile(finalFilePath);
            WordOperation.deleteTempFile(s2);

            // 四、提供的最终成果
            //临时文件名称
            String thirdFileName = "提供的最终成果";
            //富文本内容
            String cgnrAndXs = htbz.getCgnrAndXs(); //最终成果内容及形式
            String cgYsFf = htbz.getCgYsFf(); //成果验收方式
            String cgYsBz = htbz.getCgYsBz(); //成果验收标准

            //内容补充
            String thirdHtmlContext = "<p><b>1、最终成果内容及形式</b></p>"
                    + cgnrAndXs
                    + "<p></p><p></p><p><b>2、成果验收方式</b></p>"
                    + cgYsFf
                    + "<p></p><p></p><p><b>3、成果验收标准</b></p>"
                    + cgYsBz;

            String s3 = WordOperation.htmlStringToWord(thirdHtmlContext, thirdFileName, "四、提供的最终成果");
            //去水印
            WordOperation.removeWaterMark(s3, 69);
            //第三次合并
            String finalFilePath3 = WordOperation.mergeDocxFile(finalFilePath2, s3, profile + temporaryFilePath + "thirdMergeDoc.docx");

            WordOperation.removeWaterMark(finalFilePath3, 69);
            //删除临时文件
            WordOperation.deleteTempFile(finalFilePath2);
            WordOperation.deleteTempFile(s3);

            //年度计划  ---  start
            //开始日期 ksRq  结束日期 jsRq  主要内容 yfNr 阶段目标 jdMb
            HtglHtbz getNdJh = htglHtbzService.selectHtglHtbzNdjhByHtbzId(htbzId);
            List<HtglHtbzNdjh> NdjhList = getNdJh.getHtglHtbzNdjhList(); //年度计划内容及考核目标

            String ndjhListToHtml = ndjhListToHtml(NdjhList);

            //内容补充
            String fourthHtmlContext = "<p><b> </b></p>"
                    + ndjhListToHtml;

            String ndjhFileName = "年度计划表";
            String s4 = WordOperation.htmlStringToWord(fourthHtmlContext, ndjhFileName, "五、年度计划内容及考核目标");

            //去水印
            WordOperation.removeWaterMark(s4, 69);
            //第四次合并
            String finalFilePath4 = WordOperation.mergeDocxFile(finalFilePath3, s4, profile + temporaryFilePath + "fourMergeDoc.docx");
            WordOperation.removeWaterMark(finalFilePath4, 69);

            //删除临时文件
            WordOperation.deleteTempFile(finalFilePath3);
            WordOperation.deleteTempFile(s4);

            finalMergeFilePath = finalFilePath4;
        //年度计划  ---  end
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> lastMap = new HashMap<>();

        BigDecimal xmZjf = htbz.getXmZjf(); //项目总经费
        BigDecimal jfZf = htbz.getJfZf(); //甲方支付
        BigDecimal yfZc = htbz.getYfZc(); //乙方自筹
        lastMap.put("xmZjf", xmZjf);
        lastMap.put("jfZf", jfZf);
        lastMap.put("yfZc", yfZc);
        //项目预算经费
        HtglHtbz getYsJf = htglHtbzService.selectHtglHtbzYsJfByHtbzId(htbzId);
        List<HtglHtbzYsjf> ysJfList = getYsJf.getHtglHtbzYsjfList();
        IntStream.range(0, ysJfList.size())
                .forEach(i -> {
                    HtglHtbzYsjf item = ysJfList.get(i);
                    item.setNumNo(i + 1);
                });
        lastMap.put("ysJfList", ysJfList);

        BigDecimal htZe = htbz.getHtZe(); //合同总额
        BigDecimal jfToYf = htbz.getJfToYf(); //甲方向乙方提供经费
        lastMap.put("htZe", htZe);
        lastMap.put("jfToYf", jfToYf);
        //项目经费支付计划
        HtglHtbz getZfJh = htglHtbzService.selectHtglHtbzZfJhByHtbzId(htbzId);
        List<HtglHtbzZfjh> zfjhList = getZfJh.getHtglHtbzZfjhList();
        // 创建一个SimpleDateFormat对象，用于格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 遍历列表并转换日期
        for (HtglHtbzZfjh item : zfjhList) {
            Date nd = item.getNd(); // 假设getNd()方法返回Date类型的nd属性
            if (nd != null) {
                String newNd = sdf.format(nd);
                item.setNewNd(newNd);
            }
        }
        lastMap.put("zfjhList", zfjhList);

        //课题参加人员表
        HtglHtbz getCdRy = htglHtbzService.selectHtglHtbzCdRyByHtbzId(htbzId);
        List<HtglHtbzCdry> cdRyList = getCdRy.getHtglHtbzCdryList();
        // 遍历列表并将职称字典转换为值
        for (HtglHtbzCdry item : cdRyList) {
            String zhiChen = item.getZhiChen(); // 假设getNd()方法返回Date类型的nd属性
            if (zhiChen != null) {
                String zc = DictUtils.getDictLabel("rcpt_zc", zhiChen);//负责人性别
                item.setZhiChen(zc);
            }
        }
        lastMap.put("cdRyList", cdRyList);

        //导出
        String lastFileName = "htBz.docx"; //合同名称.docx
        //获取yml配置地址
        String suffixDir = profile + temporaryFilePath;
        String strName = WordUtil.easyPoiExport("static/word/htbz/htbz2.docx", suffixDir, lastFileName, lastMap, request, response);

        //ktName
        String lastFinalFileName = htbz.getHtName() + ".docx";
        //合并
        String finalPath = WordOperation.mergeDocxFile(finalMergeFilePath, suffixDir + lastFileName, profile + "/upload/" + lastFinalFileName);

        //去水印
        try {
            String filePath = WordOperation.removeWaterMark(finalPath, 69);
            //删除临时文件
            WordOperation.deleteTempFile(finalMergeFilePath);
            WordOperation.deleteTempFile(suffixDir + lastFileName);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success(lastFinalFileName);
    }

    /**
     * 年度计划 生成 html
     */
    private String ndjhListToHtml(List<HtglHtbzNdjh> NdjhList) {
        String resultStr = "";
//        1、【2023-02 ~ 2023-03】
//        1）主要内容：
//        机组尾水管、导水机构、转动部分和机组总装方案编制。
//        2）考核目标：
//        施工方案优化、上报施工方案并审批。
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM");
        for (int i = 1; i <= NdjhList.size(); i++) {
            HtglHtbzNdjh ndjh = NdjhList.get(i - 1);
            String ksTime = simple.format(ndjh.getKsRq());
            String endTime = simple.format(ndjh.getJsRq());
            resultStr += "<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + i + "、【" + ksTime + " ~ " + endTime + "】</b><br />";
            resultStr += "<b>1）主要内容：</b><br />";
            resultStr += "<b>&nbsp;&nbsp;</b>" + ndjh.getYfNr() + "<br />";
            resultStr += "<b>2）考核目标：</b><br />";
            resultStr += "<b>&nbsp;&nbsp;</b>" + ndjh.getJdMb() + "<br /><br />";
        }
        return resultStr;
    }
}
